package com.kc.gb.device.common.properties;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;

@Slf4j
@Configuration
public class DeviceConfiguration {

    @Value("${hostIP:}")
    private String hostIP;

    @Bean
    public DeviceProperties deviceProperties() throws Exception {
        log.info("ApplicationDevice HostIP:{}", hostIP);
        return DeviceConfiguration.getDeviceProperties();
    }

    public static DeviceProperties getDeviceProperties() throws Exception {
        InputStream inputStream = DeviceConfiguration.class.getResourceAsStream("/application-device.yml");
        File file = new File(getConfigPath());
        if (!file.exists()) {
            FileUtil.copyFile(inputStream, file);
        }
        log.info("ApplicationDeviceConfig:{}", file.getAbsolutePath());
        DeviceProperties origin = YamlHelper.loadFromYaml(file,DeviceProperties.class);
        log.info("origin:{}", JSON.toJSONString(origin));
        return origin;
    }

    public static String getConfigPath() throws URISyntaxException {
        String userDir = System.getProperty("user.dir");
        String configPath = userDir + File.separator + "config"+ File.separator + "application-device.yml";
        log.info("DeviceConfigPath:{}", configPath);
        return configPath;
    }
}
